package com.ruoyi.merchant.service.impl;

import com.ruoyi.merchant.service.FacePPOCRService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class FacePPOCRServiceImpl implements FacePPOCRService {
    @Value("${facepp.api.url}")
    private String apiUrl;

    @Value("${facepp.api.key}")
    private String apiKey;

    @Value("${facepp.api.secret}")
    private String apiSecret;
    @Override
    public String recognizeBusinessLicense(File imageFile) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(apiUrl);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("api_key", apiKey, ContentType.TEXT_PLAIN);
            builder.addTextBody("api_secret", apiSecret, ContentType.TEXT_PLAIN);
            builder.addBinaryBody("image_file", imageFile, ContentType.APPLICATION_OCTET_STREAM, imageFile.getName());

            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    return EntityUtils.toString(responseEntity);
                }
            }
        }
        return null;
    }
}
